package th.retrofit.lib;

/**
 * https://leetcode-cn.com/problems/spiral-matrix-ii/
 * 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
 */
public class Solution59 {

    public int[][] generateMatrix(int n) {
        int idx = 1;
        int[][] matrix = new int[n][n];
        int left = 0, right = n - 1, top = 0, bottom = n - 1;
        while (left <= right && top <= bottom) {
            int column = left, row = top;
            for (; column <= right; column++) {
                matrix[row][column] = idx++;
            }
            column--;
            for (row++; row <= bottom; row++) {
                matrix[row][column] = idx++;
            }
            row--;
            for (column--; column >= left; column--) {
                matrix[row][column] = idx++;
            }
            column++;
            for (row--; row > top; row--) {
                matrix[row][column] = idx++;
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return matrix;
    }

    public static void main(String[] args) {
        int n = 2;
        int[][] matrix = new Solution59().generateMatrix(n);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(matrix[i][j]);
                System.out.print(", ");
            }
            System.out.println();
        }
    }
}
